from rest_framework import serializers
from .models import SatelliteSchedule
from project_nav.serializers import SatelliteSerializer


class SatelliteScheduleSerializer(serializers.ModelSerializer):
    """
    卫星排程序列化器
    """
    satellite_info = SatelliteSerializer(source='satellite', read_only=True)
    task_count = serializers.SerializerMethodField()
    total_duration = serializers.SerializerMethodField()
    
    class Meta:
        model = SatelliteSchedule
        fields = [
            'id',
            'satellite',
            'satellite_info',
            'schedule_info',
            'task_count',
            'total_duration',
            'created_at',
            'updated_at'
        ]
        read_only_fields = ['created_at', 'updated_at']
    
    def get_task_count(self, obj):
        """获取任务块数量"""
        return obj.get_task_count()
    
    def get_total_duration(self, obj):
        """获取总持续时间"""
        return obj.get_total_duration()
    
    def validate_schedule_info(self, value):
        """
        验证排程信息格式
        """
        if not isinstance(value, (list, dict)):
            raise serializers.ValidationError("排程信息必须是列表或字典格式")
        
        # 如果是列表格式，验证每个任务块的基本字段
        if isinstance(value, list):
            for i, task in enumerate(value):
                if not isinstance(task, dict):
                    raise serializers.ValidationError(f"任务块 {i+1} 必须是字典格式")
                
                required_fields = ['task_name', 'duration']
                for field in required_fields:
                    if field not in task:
                        raise serializers.ValidationError(f"任务块 {i+1} 缺少必需字段: {field}")
                
                # 验证持续时间是正整数
                try:
                    duration = int(task['duration'])
                    if duration <= 0:
                        raise ValueError()
                except (ValueError, TypeError):
                    raise serializers.ValidationError(f"任务块 {i+1} 的持续时间必须是正整数")
        
        return value


class SatelliteScheduleCreateSerializer(serializers.ModelSerializer):
    """
    创建卫星排程的序列化器
    """
    class Meta:
        model = SatelliteSchedule
        fields = ['satellite', 'schedule_info']
    
    def validate_schedule_info(self, value):
        """验证排程信息格式"""
        serializer = SatelliteScheduleSerializer()
        return serializer.validate_schedule_info(value)